/**查找分页控件 -> 请求下一页 -> 增删元素 -> 加载在页面 */
async function loadNextPage() {
  let [lastNrPage] = [...document.getElementsByClassName('nr_page')].slice(-1)
  let url = lastNrPage.lastChild.href

  const response = await fetch(url)
  const decoder = new TextDecoder('gbk')
  const html = decoder.decode(await response.arrayBuffer())

  let div = document.createElement('div')
  div.innerHTML = html
  div.querySelector('.main_content').style.marginBottom = '0px'
  div.querySelector('.main_content').style.border = 'none'
  let pageDom = div.querySelectorAll('.nr_page')
  let alink = document.createElement('a')
  alink.href = url
  alink.innerText = '本页'
  pageDom.forEach((item) => item.insertBefore(alink.cloneNode(true), item.children[1]))
  div.querySelector('.nr_content').style.background = '#efefef'

  $chromePlugin.cleanPage(div, ['.footer', '.head'])

  let [lastContent] = [...document.getElementsByClassName('nr_content')].slice(-1)
  lastContent.parentNode.appendChild(div)
  return {div, url}
}

/**从页面获取书名 */
function getBookName() {
  let bookName = ''
  let introduceEl = document.getElementsByClassName('introduce')
  if (introduceEl.length) {
    bookName = introduceEl[0].querySelector('h1').innerText
  }

  let articleTitleEl = document.getElementsByClassName('articletitle')
  if (articleTitleEl.length) {
    bookName = articleTitleEl[0].querySelector('a').innerText
  }
  return bookName
}

/**_addObserver传入targetSelector、chapterTitleSelector*/
function addObserver(dom = document, url = location.href) {
  _addObserver('.nr_content', '.nr_title h3', dom, url)
}

/**添加段落之间的间隔， 提升阅读体验 */
function addSpace() {
  let dom = document.getElementById('articlecontent')
  if (!dom) return
  console.log('✅ handle #articlecontent')
  let brNodeList = dom.querySelectorAll('br')
  for (let i = 0; i < brNodeList.length; i++) {
    let brNode = brNodeList[i]
    if (i == 0 && $chromePlugin.getNextNodeName(brNode) == 'BR') break
    dom.insertBefore(document.createElement('br'), brNode)
  }
}

$chromePlugin.loadQueueFn.push(addSpace)
